package net.adetech.crj.utils;

import com.alibaba.fastjson.JSONObject;
import net.adetech.framework.entity.ServiceRequest;
import net.adetech.framework.entity.ServiceResponse;
import net.adetech.framework.utils.SerializeUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ServiceUtil {

    @Value("${mid_service.url}")
    public String midServiceUrl;


    public ServiceResponse call(ServiceRequest request)
    {
        String requestString = SerializeUtil.objectToString(request);
        try {
            List<NameValuePair> paramList = new ArrayList<NameValuePair>();
            paramList.add(new BasicNameValuePair("data",requestString));
            HttpEntity reqEntity = new UrlEncodedFormEntity(paramList,"utf-8");
            HttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(midServiceUrl);
            post.setEntity(reqEntity);
            //post.setHeader("Authorization","APPCODE f77530e7d1324c3bbd47c819aa33711c");

            HttpResponse httpResponse = client.execute(post);
            String responseString = EntityUtils.toString(httpResponse.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(responseString);
            String resultString = jsonObject.getString("result");
            ServiceResponse serviceResponse = (ServiceResponse) SerializeUtil.stringToObject(resultString);
            return serviceResponse;
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return  null;
    }


    public ServiceResponse call(String serviceName,ServiceRequest request)
    {
        request.setServiceName(serviceName);
        return call(request);
    }
}
